# https://xxcapp.xidian.edu.cn/site/ncov/xidiandailyup

#引入包位置
import sys


from urllib import parse

import urllib3
import requests
import time
import json
# smtplib 用于邮件的发信动作
import smtplib
from email.mime.text import MIMEText
# email 用于构建邮件内容
from email.header import Header


class YqtUpload:
    def __init__(self, username1, password1, addr1):
        self.username = username1
        self.password = password1
        self.addr = addr1
    # 通过账号密码获取cookies

    def getCookie(self):
        url_login = "https://xxcapp.xidian.edu.cn/uc/wap/login/check"
        data_login = {
            # 用户信息修改
            "username": self.username,
            "password": self.password
        }
        # Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome /77.0.3865.120 Safari/537.36
        headers_login = {
            "User-Agent":
                "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62"
        }

        while True:
            num = 1
            try:
                r = requests.post(url_login, data=data_login, headers=headers_login)
                r.raise_for_status()
                break
            except:
                time.sleep(1)
                num += 1
            finally:
                if num > 5:
                    print("ALERT: TimeOutError...")
                    break
        cookies_dict = requests.utils.dict_from_cookiejar(r.cookies)
        # 使用utils.dict_from_cookiejar 将cookies数据类型转化为字典
        self.cookies = parse.urlencode(cookies_dict).replace("&", ";")

    # 将疫情通数据上传

    def dataUpload(self):
        url_upload = "https://xxcapp.xidian.edu.cn/xisuncov/wap/open-report/save"
        data_upload = {
            "sfzx": "1",  # 是否在校
            "tw": "2",  # 体温

            # 地址修改
            # 这里可以看一下请求头中的地址参数然后复制过来
            "address": "陕西省西安市长安区兴隆街道外环北路西安电子科技大学南校区",
            "geo_api_info": '{"type":"complete","position":{"Q":34.127457682292,"R":108.83447726779599,'
                            '"lng":108.834477,"lat":34.127458},"location_type":"html5",'
                            '"message":"Get ipLocation failed.Get geolocation success.'
                            'Convert Success.Get address success.","accuracy":74,"isConverted":true,'
                            '"status":1,"addressComponent":{"citycode":"029",'
                            '"adcode":"610116","businessAreas":[],"neighborhoodType":"","neighborhood":"","building":"",'
                            '"buildingType":"","street":"雷甘路","streetNumber":"266号","country":"中国","province":"陕西省",'
                            '"city":"西安市","district":"长安区","towncode":"610116016000","township":"兴隆街道"},'
                            '"formattedAddress":"陕西省西安市长安区兴隆街道外环北路西安电子科技大学南校区",'
                            '"roads":[],"crosses":[],"pois":[],"info":"SUCCESS"}',
            # "area": "xxxxxx",
            # "province": "xxxxx",
            # "city": "xxxxx",

            "sfcyglq": "0",  # 是否隔离期
            "sfyzz": "0",  # 是否有症状
            "qtqk": "",  # 其他情况
            "ymtys": "0",  # 一码通颜色

        }
        headers_upload = {
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62",
            "cookie": self.cookies
        }
        try:
            r = requests.post(url_upload, headers=headers_upload, data=data_upload)
            r.raise_for_status()
        except:
            print("upload failed!")
            exit(0)
        response = json.loads(r.text)
        print(response['m'] + " " + time.asctime(time.localtime(time.time())))

    def emails(self):
        # 发信方的信息：发信邮箱，QQ 邮箱授权码 改成自己的
        from_addr = 'xxx@qq.com'
        password = 'xxx'

        # 收信方邮箱
        to_addr = self.addr

        # 发信服务器
        smtp_server = 'smtp.qq.com'

        # 邮箱正文内容，第一个参数为内容，第二个参数为格式(plain 为纯文本)，第三个参数为编码
        msg = MIMEText('晨午晚检已打卡', 'plain', 'utf-8')

        # 邮件头信息
        msg['From'] = Header(from_addr)
        msg['To'] = Header(to_addr)
        msg['Subject'] = Header('晨午晚检')

        # 开启发信服务，这里使用的是加密传输
        server = smtplib.SMTP_SSL(smtp_server)
        server.connect(smtp_server, 465)
        # 登录发信邮箱
        server.login(from_addr, password)
        # 发送邮件
        server.sendmail(from_addr, to_addr, msg.as_string())
        # 关闭服务器
        server.quit()

# https://xxcapp.xidian.edu.cn/uc/wap/login/check


# xxx处写入自己的信息
x2 = YqtUpload("xxx", "xxx", "xxx")
x2.getCookie()
x2.dataUpload()
#邮箱功能可随意加
#x2.emails()  
